package com.hzl;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hzl.sample.AlphaAdapter;
import com.hzl.sample.LetterBarView;
import com.hzl.sample.ViewHolder;
import com.yao.component.circle.R;
import java.util.ArrayList;
import java.util.List;

public class ContactsActivity extends Activity implements RecyclerClickListener.OnItemClickLitener, View.OnClickListener {

    private ImageView img_search;
    private ListView eListView;
    private RelativeLayout rl_search;
    private EditText searchView;
    private RelativeLayout all;
    private ArrayList<UserInfoBean> userinfolist = new ArrayList<UserInfoBean>();
    private ArrayList<UserInfoBean> userinfosearchlist = new ArrayList<UserInfoBean>();
    private AlphaAdapter<UserInfoBean> userinfoAdapter;
    private LetterBarView letterBar;
    private RecyclerView recycler;
    private TextView tv_right;
    private TextView tv_left;
    private MyAdapter myAdapter;
    private String type;
    private ArrayList<UserInfoBean> personList;
    private ArrayList<UserInfoBean> listimg;
    private TextView title_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);
        initDate();
        title_name = (TextView) findViewById(R.id.title_name);
        recycler = (RecyclerView) findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManagerWrapper(this, LinearLayoutManager.HORIZONTAL, false));
        myAdapter = new MyAdapter();
        recycler.setAdapter(myAdapter);
        myAdapter.setOnItemClickLitener(this);
        img_search = (ImageView) findViewById(R.id.img_search);
        tv_right = (TextView) findViewById(R.id.tv_right);
        tv_right.setOnClickListener(this);
        tv_left = (TextView) findViewById(R.id.tv_left);
        tv_left.setOnClickListener(this);
        Intent intent = getIntent();
        type = intent.getStringExtra("type");
        switch (type) {
            case Constants.STARTREMIND:
                title_name.setText("提醒谁看");
                listimg = (ArrayList<UserInfoBean>) intent.getSerializableExtra("listimg");
                toplist.clear();
                for (int i = 0; i < userinfolist.size(); i++) {
                    for (int j = 0; j < listimg.size(); j++) {
                        if (userinfolist.get(i).getHeadImg() == listimg.get(j).getHeadImg()){
                            userinfolist.get(i).setStatus(2);
                            userinfolist.get(i).setCheckimg(R.drawable.tick_select);
                        }
                    }
                }
                if (listimg != null){
                    for (int i = 0; i < listimg.size(); i++) {
                        toplist.add(listimg.get(i).getHeadImg());
                    }
                    if (toplist.size() == 0) {
                        tv_right.setText("确定");
                        tv_right.setTextColor(Color.parseColor("#ffffff"));
                    } else {
                        tv_right.setText("确定(" + toplist.size() + "/10)");
                        tv_right.setTextColor(Color.parseColor("#09bb07"));
                    }

                    ViewGroup.LayoutParams layoutParams = recycler.getLayoutParams();
                    int with = DensityUtil.dip2px(ContactsActivity.this, 45);
                    int size = toplist.size();
                    if (size > 6) {
                        layoutParams.width = 6 * with;
                        recycler.smoothScrollToPosition(size);
                        img_search.setVisibility(View.GONE);
                    }
                    if (size > 0 && size <= 6) {
                        layoutParams.width = size * with;
                        img_search.setVisibility(View.GONE);
                    }
                    if (size == 0) {
                        layoutParams.width = 0;
                        img_search.setVisibility(View.VISIBLE);

                    }
                    recycler.setLayoutParams(layoutParams);
                }
                break;

            case Constants.NEW_START_LABEL:
                title_name.setText("选择联系人");
                break;

            case Constants.ADD_LABEL:
                title_name.setText("选择联系人");
                personList = (ArrayList<UserInfoBean>) intent.getSerializableExtra("personList");
                for (int i = 0; i < userinfolist.size(); i++) {
                    for (int j = 0; j < personList.size(); j++) {
                        if (userinfolist.get(i).getHeadImg() == personList.get(j).getHeadImg()){
                            userinfolist.get(i).setStatus(3);
                            userinfolist.get(i).setCheckimg(R.drawable.tick_gray_select);
                        }
                    }
                }
                break;

            default:
                break;
        }
        initUI(type);

    }

    private List<Integer> toplist = new ArrayList<Integer>();

    private void initDetial() {
        eListView.setOnItemClickListener(new AlphaAdapter.OnItemClickWrapperListener<UserInfoBean>() {

            @Override
            public void onItemClick(UserInfoBean itemData) {
                if (Constants.NEW_START_LABEL.equals(type) || Constants.ADD_LABEL.equals(type)){
                        if (itemData.getStatus() == 2) {
                            itemData.setStatus(1);
                            itemData.setCheckimg(R.drawable.tick);
                            int headImg = itemData.getHeadImg();
                            int i = toplist.indexOf(headImg);
                            toplist.remove(i);
                            for (int j = 0; j < userinfolist.size(); j++) {
                                if (userinfolist.get(j).getHeadImg() == headImg) {
                                    userinfolist.get(j).setStatus(1);
                                }
                            }
                            userinfoAdapter.setData(userinfolist);
                            userinfoAdapter.notifyDataSetChanged();
                            searchView.setText("");
                        } else if (itemData.getStatus() == 1) {
                            itemData.setStatus(2);
                            itemData.setCheckimg(R.drawable.tick_select);
                            int headImg = itemData.getHeadImg();
                            toplist.add(headImg);
                            searchView.setText("");
                        }
                        if (toplist.size() == 0) {
                            tv_right.setText("确定");
                            tv_right.setClickable(false);
                            tv_right.setTextColor(Color.parseColor("#ffffff"));
                        } else {
                            tv_right.setText("确定(" + toplist.size() + ")");
                            tv_right.setClickable(true);
                            tv_right.setTextColor(Color.parseColor("#09bb07"));
                        }
                }else {
                    if (toplist.size() < 10 && toplist.size() >= 0) {
                        if (itemData.getStatus() == 2) {
                            itemData.setStatus(1);
                            itemData.setCheckimg(R.drawable.tick);
                            int headImg = itemData.getHeadImg();
                            int i = toplist.indexOf(headImg);
                            toplist.remove(i);
                            for (int j = 0; j < userinfolist.size(); j++) {
                                if (userinfolist.get(j).getHeadImg() == headImg) {
                                    userinfolist.get(j).setStatus(1);
                                }
                            }
                            userinfoAdapter.setData(userinfolist);
                            userinfoAdapter.notifyDataSetChanged();
                            searchView.setText("");
                        } else if (itemData.getStatus() == 1) {
                            itemData.setStatus(2);
                            itemData.setCheckimg(R.drawable.tick_select);
                            int headImg = itemData.getHeadImg();
                            toplist.add(headImg);
                            searchView.setText("");
                        }
                        if (toplist.size() == 0) {
                            tv_right.setText("确定");
                            tv_right.setTextColor(Color.parseColor("#ffffff"));
                        } else {
                            tv_right.setText("确定(" + toplist.size() + "/10)");
                            tv_right.setTextColor(Color.parseColor("#09bb07"));
                        }
                        userinfoAdapter.notifyDataSetChanged();
                    } else if (toplist.size() == 10) {
                        if (itemData.getStatus() == 2) {
                            itemData.setStatus(1);
                            itemData.setCheckimg(R.drawable.tick);
                            int headImg = itemData.getHeadImg();
                            int i = toplist.indexOf(headImg);
                            toplist.remove(i);
                            searchView.setText("");
                        } else {
                            initDialog();
                        }
                    }
                }
                initTopListAdd();
            }
        });
    }

    private void initDialog() {
        final AlertDialog builder = new AlertDialog(ContactsActivity.this);
        builder.setTitle("提示");
        builder.setMessage("最多选择10人");
        builder.setCancelable(false);
        builder.setPositiveButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();

            }
        });
    }

    private void initTopListAdd() {
        ViewGroup.LayoutParams layoutParams = recycler.getLayoutParams();
        int with = DensityUtil.dip2px(ContactsActivity.this, 45);
        int size = toplist.size();
        if (size > 6) {
            layoutParams.width = 6 * with;
//            recycler.scrollToPosition(size);
            recycler.smoothScrollToPosition(size);
            img_search.setVisibility(View.GONE);
        }
        if (size > 0 && size <= 6) {
            layoutParams.width = size * with;
            img_search.setVisibility(View.GONE);
        }
        if (size == 0) {
            layoutParams.width = 6;
            img_search.setVisibility(View.VISIBLE);

        }
        recycler.setLayoutParams(layoutParams);
        myAdapter.notifyItemRangeChanged(0,myAdapter.getItemCount());
        myAdapter.setOnItemClickLitener(this);
    }

    private void initUI(final String type) {
        searchView = (EditText) findViewById(R.id.ed_search);
        searchView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.equals("") || s == null) {
                    userinfoAdapter.setData(userinfolist);
                    userinfoAdapter.notifyDataSetChanged();
                } else {
                    userinfosearchlist.clear();
                    for (int i = 0; i < userinfolist.size(); i++) {
                        UserInfoBean useinfo = userinfolist.get(i);
                        if (useinfo.getUserAlpha().toLowerCase().contains(searchView.getText().toString().toLowerCase())
                                || useinfo.getUserName().contains(searchView.getText().toString())) {
                            userinfosearchlist.add(userinfolist.get(i));
                        }
                    }
                    userinfoAdapter.setData(userinfosearchlist);
                    userinfoAdapter.notifyDataSetChanged();
                }
            }
        });
        all = (RelativeLayout) findViewById(R.id.all);
        rl_search = (RelativeLayout) findViewById(R.id.rl_search);
        userinfoAdapter = new AlphaAdapter<UserInfoBean>(ContactsActivity.this, userinfolist) {

            @Override
            public void bindOriginData(int position, View convertView, final UserInfoBean itemData) {
                ImageView headimage = ViewHolder.getView(convertView, R.id.head);
                TextView username = ViewHolder.getView(convertView, R.id.name);
//                CheckBox trusteeshipSignCheckBox = ViewHolder.getView(convertView, R.id.checkBox);
                ImageView img_box = ViewHolder.getView(convertView, R.id.img_box);
                img_box.setImageResource(itemData.getCheckimg());
                headimage.setImageResource(itemData.getHeadImg());
                username.setText(itemData.getUserName());
//                switch (itemData.getStatus()) {
//                    case 1:
////                        trusteeshipSignCheckBox.setChecked(false);
//                        break;
//                    case 2:
////                        trusteeshipSignCheckBox.setChecked(true);
//                        break;
//                    case 3:
//                        img_box.setVisibility(View.VISIBLE);
////                        trusteeshipSignCheckBox.setVisibility(View.GONE);
////                        trusteeshipSignCheckBox.setClickable(false);
//                        break;
//                    default:
//                        break;
//                }
                //需要在adapter里面改变check的状态，否则跟OnItem监听没有同步
//                trusteeshipSignCheckBox.setOnClickListener(new View.OnClickListener() {
                img_box.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (Constants.NEW_START_LABEL.equals(type) || Constants.ADD_LABEL.equals(type)){
                                if (itemData.getStatus() == 2) {
                                    itemData.setStatus(1);
                                    itemData.setCheckimg(R.drawable.tick);
                                    int headImg = itemData.getHeadImg();
                                    int i = toplist.indexOf(headImg);
                                    toplist.remove(i);
                                    for (int j = 0; j < userinfolist.size(); j++) {
                                        if (userinfolist.get(j).getHeadImg() == headImg) {
                                            userinfolist.get(j).setStatus(1);
                                        }
                                    }
                                    userinfoAdapter.setData(userinfolist);
                                    userinfoAdapter.notifyDataSetChanged();
                                    searchView.setText("");
                                } else if (itemData.getStatus() == 1) {
                                    itemData.setStatus(2);
                                    itemData.setCheckimg(R.drawable.tick_select);
                                    int headImg = itemData.getHeadImg();
                                    toplist.add(headImg);
                                    searchView.setText("");
                                }
                                if (toplist.size() == 0) {
                                    tv_right.setText("确定");
                                    tv_right.setClickable(false);
                                    tv_right.setTextColor(Color.parseColor("#ffffff"));
                                } else {
                                    tv_right.setText("确定(" + toplist.size() + ")");
                                    tv_right.setClickable(true);
                                    tv_right.setTextColor(Color.parseColor("#09bb07"));
                                }
                                initTopListAdd();
                        }else {
                            if (toplist.size() < 10 && toplist.size() >= 0) {
                                if (itemData.getStatus() == 2) {
                                    itemData.setStatus(1);
                                    itemData.setCheckimg(R.drawable.tick);
                                    int headImg = itemData.getHeadImg();
                                    int i = toplist.indexOf(headImg);
                                    toplist.remove(i);
                                    for (int j = 0; j < userinfolist.size(); j++) {
                                        if (userinfolist.get(j).getHeadImg() == headImg) {
                                            userinfolist.get(j).setStatus(1);
                                        }
                                    }
                                    userinfoAdapter.setData(userinfolist);
                                    userinfoAdapter.notifyDataSetChanged();
                                    searchView.setText("");
                                } else if (itemData.getStatus() == 1) {
                                    itemData.setStatus(2);
                                    itemData.setCheckimg(R.drawable.tick_select);
                                    int headImg = itemData.getHeadImg();
                                    toplist.add(headImg);
                                    searchView.setText("");
                                }
                                if (toplist.size() == 0) {
                                    tv_right.setText("确定");
                                    tv_right.setTextColor(Color.parseColor("#ffffff"));
                                } else {
                                    tv_right.setText("确定(" + toplist.size() + "/10)");
                                    tv_right.setTextColor(Color.parseColor("#09bb07"));
                                }
                                initTopListAdd();
                            } else if (toplist.size() == 10) {
                                if (itemData.getStatus() == 2) {
                                    itemData.setStatus(1);
                                    itemData.setCheckimg(R.drawable.tick);
                                    int headImg = itemData.getHeadImg();
                                    int i = toplist.indexOf(headImg);
                                    toplist.remove(i);
                                    searchView.setText("");
                                } else {
                                    initDialog();
                                }
                            }
                        }
                    }
                });
            }
        };

        eListView = (ListView) findViewById(R.id.contacts_list);
        eListView.setAdapter(userinfoAdapter);

        initDetial();

        letterBar = (LetterBarView) findViewById(R.id.letter_bar);
        letterBar.setOnLetterSelectListener(new LetterBarView.OnLetterSelectListener() {

            @Override
            public void onLetterSelect(String s) {
                if (s.equalsIgnoreCase("#")) {
                    eListView.setSelection(0);
                } else {
                    if (userinfoAdapter.containsAlpha(s)) {
                        eListView.setSelection(userinfoAdapter.getAlphaPosition(s));
                    }
                }
            }
        });

    }

    private void initDate() {
        for (int i = 0; i < 17; i++) {
            String shouzimu = HypyUtil.cn2py(UserInfoConstants.names[i]);
            String s = shouzimu.toUpperCase();
            userinfolist.add(new UserInfoBean(i + 1, UserInfoConstants.heads[i], UserInfoConstants.names[i], s, 1,R.drawable.tick));
            userinfosearchlist.add(new UserInfoBean(i + 1, UserInfoConstants.heads[i], UserInfoConstants.names[i], s, 1,R.drawable.tick));
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        Integer imgremove = toplist.get(position);
        toplist.remove(position);
        myAdapter.notifyItemRangeChanged(position, myAdapter.getItemCount());
        for (int i = 0; i < userinfolist.size(); i++) {
            if (userinfolist.get(i).getHeadImg() == imgremove) {
                userinfolist.get(i).setStatus(1);
                userinfolist.get(i).setCheckimg(R.drawable.tick);
            }
        }
        userinfoAdapter.setData(userinfolist);
        userinfoAdapter.notifyDataSetChanged();

        if (toplist.size() == 0) {
            tv_right.setText("确定");
            tv_right.setTextColor(Color.parseColor("#ffffff"));
        } else {
            if (Constants.NEW_START_LABEL.equals(type) || Constants.ADD_LABEL.equals(type)){
                tv_right.setText("确定");
            }else {
                tv_right.setText("确定(" + toplist.size() + "/10)");
            }
        }

        ViewGroup.LayoutParams layoutParams = recycler.getLayoutParams();
        int with = DensityUtil.dip2px(ContactsActivity.this, 45);
        int size = toplist.size();
        if (size > 6) {
            layoutParams.width = 6 * with;
            img_search.setVisibility(View.GONE);
        }
        if (size > 0 && size <= 6) {
            layoutParams.width = size * with;
            img_search.setVisibility(View.GONE);
        }
        if (size == 0) {
            layoutParams.width = 0;
            img_search.setVisibility(View.VISIBLE);

        }
        recycler.setLayoutParams(layoutParams);
        recycler.scrollToPosition(6);

    }

    @Override
    public void onItemLongClick(View view, int position) {

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_right) {
            Intent intent = new Intent();
            ArrayList<UserInfoBean> list = new ArrayList<UserInfoBean>();
            for (int i = 0; i < userinfolist.size(); i++) {
                UserInfoBean userInfoBean = userinfolist.get(i);
                if (userInfoBean.getStatus() == 2) {
                    if (Constants.ADD_LABEL.equals(type)) {
                        personList.add(userInfoBean);
                        intent.putExtra("UserInfoBean", personList);
                    }else {
                        list.add(userInfoBean);
                        intent.putExtra("UserInfoBean", list);
                    }
                }
            }
            setResult(Constants.CODE_FRIEND_LIST, intent);
            finish();

        } else if (v.getId() == R.id.tv_left) {
            finish();
        }
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

        private RecyclerClickListener.OnItemClickLitener onItemClickLitener;

        @Override
        public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(ContactsActivity.this).inflate(R.layout.item_top, parent, false);
            MyViewHolder holder = new MyViewHolder(inflate);
            holder.img = (ImageView) inflate.findViewById(R.id.img);
            return holder;
        }

        @Override
        public void onBindViewHolder(final MyAdapter.MyViewHolder holder, final int position) {
            holder.img.setImageResource(toplist.get(position));
            if (onItemClickLitener != null) {
                holder.img.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onItemClickLitener.onItemClick(holder.img, position);
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return toplist.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {

            public MyViewHolder(View itemView) {
                super(itemView);
            }

            ImageView img;
        }

        public void setOnItemClickLitener(RecyclerClickListener.OnItemClickLitener onItemClickLitener) {
            this.onItemClickLitener = onItemClickLitener;
        }
    }
}
